<template>
    <div>
        <!--面包屑导航-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <!-- 添加 -->
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addRolesVisible = true">添加角色</el-button>
                </el-col>
            </el-row>
            <el-table :data="rolelist" border stripe>
                <!-- 展开列 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
                            v-for="(item1, i1) in scope.row.children" :key="item1.id">
                            <!-- 一级 -->
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row, item1.id)">
                                    {{ item1.authName }}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 二级和三级 -->
                            <el-col :span="19">
                                <!-- for嵌套 -->
                                <el-row v-for="(item2, i2) in item1.children" :key="item2.id"
                                    :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']">
                                    <!-- 左 二级 -->
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">
                                            {{ item2.authName }}
                                        </el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <!-- 右 三级 -->
                                    <el-col :span="18">
                                        <el-tag type="warning" v-for="(item3, i3) in item2.children" :key="item3.id"
                                            :class="[i3 === 0 ? '' : 'bdtop']" closable
                                            @close="removeRightById(scope.row, item3.id)">
                                            {{ item3.authName }}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>


                        <!-- <pre>
                        {{ 
                            scope.row
                        }}
                    </pre> -->

                    </template>
                </el-table-column>
                <!-- 引索列 -->
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="shouEditRoles(scope.row.id)">
                            编辑
                        </el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini"
                            @click="removRolesById(scope.row.id)">
                            删除
                        </el-button>
                        <el-button type="warning" icon="el-icon-setting" size="mini"
                            @click="showSetRightDialog(scope.row)">
                            分配权限
                        </el-button>


                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 分配权限 -->
        <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">
            <el-tree :props="treeProps" :data="rightslist" show-checkbox node-key="id" default-expand-all
                :default-checked-keys="defKeys" ref="treeRef"> </el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 添加角色 -->
        <el-dialog title="添加角色" :visible.sync="addRolesVisible" width="50%" @close="addRolesClosed">
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addRolesVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑 -->
        <el-dialog title="修改用户" :visible.sync="editRolesVisible" width="50%" @close="editRolesClosed">
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
                <el-form-item label="角色id">
                    <el-input v-model="editForm.roleId" disabled></el-input>
                </el-form-item>
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editRolesVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUserInfo">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {

        return {
            //默认选中的节点数组
            defKeys: [],
            treeProps: {
                label: 'authName',
                children: 'children'
            },
            rightslist: [],
            //控制分配权限对话框显示
            setRightDialogVisible: false,
            // 所有角色列表数据
            rolelist: [],
            addRolesVisible: false,
            editRolesVisible: false,
            addForm: {
                roleName: '',
                roleDesc: '',
            },
            addFormRules: {
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                ],
                roleDesc: [
                    { required: false, message: '请输入角色描述', trigger: 'blur' },
                ]

            },
            //修改表单中查询到的用户信息
            editForm: {},
            editFormRules: {
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                ],
                roleDesc: [
                    { required: false, message: '请输入角色职能', trigger: 'blur' },
                ]
            },
            //当前即将分配权限的id
            roleId: ''
        }
    },
    created() {
        this.getRolesList()
    },
    methods: {
        async getRolesList() {
            const { data: res } = await this.$http.get('roles')
            if (res.meta.status != 200) {
                return this.$message.error('获取角色列表失败')
            }
            this.rolelist = res.data
            console.log(this.rolelist)
        },
        addRolesClosed() {
            this.$refs.addFormRef.resetFields()
        },
        editRolesClosed() {
            this.$refs.editFormRef.resetFields()
        },
        addUser() {
            this.$refs.addFormRef.validate(async valid => {
                console.log(valid)
                if (!valid) return
                const { data: res } = await this.$http.post('roles', this.addForm)

                if (res.meta.status !== 201) {
                    this.$message.error('添加角色失败')
                }
                this.$message.success('添加角色成功')
                this.addRolesVisible = false //隐藏对话框
                this.getRolesList() //重新获取列表数据
            })
        },
        //编辑对话框
        async shouEditRoles(id) {
            console.log(id)
            const { data: res } = await this.$http.get('roles/' + id)
            if (res.meta.status !== 200) {
                return this.$message.error('查询角色信息失败')
            }
            this.editForm = res.data
            console.log(this.editForm)
            this.editRolesVisible = true

        },
        //修改提交
        editUserInfo() {
            this.$refs.editFormRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await this.$http.put('roles/' + this.editForm.roleId,
                    {
                        roleId: this.editForm.roleId,
                        roleName: this.editForm.roleName,
                        roleDesc: this.editForm.roleDesc
                    })
                if (res.meta.status !== 200) {
                    return this.$message.error('更新角色信息失败')
                }
                // 关闭
                this.editRolesgVisible = false
                // 刷新
                this.getRolesList()
                // 提示成功
                this.$message.success('更新角色信息成功')
            })

        },
        //删除角色
        async removRolesById(id) {
            // console.log(id)
            //弹窗
            const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)
            // 确认删除返回confirm,取消返回cancel
            // console.log(confirmResult)
            if (confirmResult !== 'confirm') {
                return this.$message.info('已取消删除')
            }
            const { data: res } = await this.$http.delete('roles/' + id)

            if (res.meta.status !== 200) {
                return this.$message.error('删除失败')
            }
            this.$message.success('删除成功')
            this.getRolesList()

        },
        //id删除权限
        async removeRightById(role, rightId) {
            //弹窗
            const confirmResult = await this.$confirm('此操作将永久删除此权限, 是否继续?',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)
            // 确认删除返回confirm,取消返回cancel
            if (confirmResult !== 'confirm') {
                return this.$message.info('已取消删除')
            }
            const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)

            if (res.meta.status !== 200) {
                return this.$message.error('删除权限失败')
            }
            this.$message.success('删除权限成功')

            // this.getRolesList()
            role.children = res.data
        },
        //分配权限
        async showSetRightDialog(role) {
            this.roleId = role.id
            //获取权限数据
            const { data: res } = await this.$http.get('rights/tree')
            if (res.meta.status !== 200) {
                return this.$message.error('获取失败')
            }
            this.rightslist = res.data
            console.log(this.rightslist)
            //递归
            this.getLeafKeys(role, this.defKeys)

            this.setRightDialogVisible = true
        },
        //递归获取角色三级权限id
        getLeafKeys(node, arr) {
            if (!node.children) {
                //不含children为三级，直接推出
                return arr.push(node.id)
            }
            node.children.forEach(item =>
                this.getLeafKeys(item, arr)
            )
        },
        //监听权限对话框的关闭
        setRightDialogClosed() {
            this.defKeys = []
        },
        //确定返回权限id
        async allotRights() {
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            // console.log(keys)
            const idStr = keys.join(',')

            const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
            if (res.meta.status !== 200) {
                return this.$message.error('分配权限失败')
            }

            this.$message.success('分配权限成功')
            this.getRolesList()
            this.setRightDialogVisible = false
        }
    }
}
</script>

<style lang="less" scoped>
.el-tag {
    margin: 7px;
}

.bdtop {
    border-top: 1px solid #eee;
}

.bdbottom {
    border-bottom: 1px solid #eee;
}

.vcenter {

    display: flex;
    align-items: center;
}
</style>